package com.zbkj.service.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zbkj.common.constants.OrderConstants;
import com.zbkj.common.constants.OrderStatusConstants;
import com.zbkj.common.constants.ProductConstants;
import com.zbkj.common.model.agent.UserStoreRelation;
import com.zbkj.common.model.merchant.Merchant;
import com.zbkj.common.model.order.MonitorOrder;
import com.zbkj.common.model.order.Order;
import com.zbkj.common.model.order.OrderDetail;
import com.zbkj.common.model.traceable.TraceableOrder;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.MerchantStoreOrderFrontSaveRequest;
import com.zbkj.common.request.PageParamRequest;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.common.exception.AppException;

import com.zbkj.common.response.MerchantSettledConfigResponse;
import com.zbkj.common.response.OrderNoResponse;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebDateUtil;
import com.zbkj.common.model.agent.MerchantStoreOrder;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.service.dao.MerchantStoreOrderDao;
import com.zbkj.service.service.*;

import com.zbkj.common.request.MerchantStoreOrderSaveRequest;
import com.zbkj.common.request.MerchantStoreOrderSearchRequest;
import com.zbkj.common.response.MerchantStoreOrderPageDataResponse;
import com.zbkj.common.response.MerchantStoreOrderDetailResponse;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author Caiyc
* @description MerchantStoreOrderServiceImpl 接口实现
* @date 2025-07-28
*/
@Service
public class MerchantStoreOrderServiceImpl extends ServiceImpl<MerchantStoreOrderDao, MerchantStoreOrder> implements MerchantStoreOrderService {

    @Resource
    private MerchantStoreOrderDao dao;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderStatusService orderStatusService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private UserStoreRelationService userStoreRelationService;


    @Override
    public Boolean create(MerchantStoreOrderSaveRequest merchantStoreOrderSaveRequest) {
        MerchantStoreOrder merchantStoreOrder = new MerchantStoreOrder();
        BeanUtils.copyProperties(merchantStoreOrderSaveRequest, merchantStoreOrder, "id");
        boolean save = save(merchantStoreOrder);
        if (!save) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "添加失败");
        }
        return save;
    }

    /**
     * 分页查询商户门店订单表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<MerchantStoreOrder>
     * @author Caiyc
     * @since 2025-07-28
     */
    @Override
    public List<MerchantStoreOrderPageDataResponse> getList(MerchantStoreOrderSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        LambdaQueryWrapper<MerchantStoreOrder> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.orderByDesc(MerchantStoreOrder::getCreateTime);
        List<MerchantStoreOrder> merchantStoreOrders = dao.selectList(lambdaQueryWrapper);
        // 添加活动状态
        List<MerchantStoreOrderPageDataResponse> merchantStoreOrderResponses = new ArrayList<>();

        merchantStoreOrders.stream().forEach(x->{
            MerchantStoreOrderPageDataResponse merchantStoreOrderResponse = new MerchantStoreOrderPageDataResponse();
            BeanUtils.copyProperties(x, merchantStoreOrderResponse);
            merchantStoreOrderResponses.add(merchantStoreOrderResponse);
        });
        return merchantStoreOrderResponses;
    }

    /**
    * 修改商户门店订单表
    * @param request
    * @return
    */
    @Override
    public boolean update(MerchantStoreOrderSaveRequest request) {
        if (ObjectUtil.isNull(request.getId()) || request.getId() < 1) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请传入商户门店订单表ID");
        }
        getByIdException(request.getId());
        MerchantStoreOrder merchantStoreOrder = new MerchantStoreOrder();
        BeanUtils.copyProperties(request, merchantStoreOrder);
        return updateById(merchantStoreOrder);
    }

    private MerchantStoreOrder getByIdException(Long id) {
        MerchantStoreOrder merchantStoreOrder = getById(id);
        if (ObjectUtil.isNull(merchantStoreOrder)) {
            throw new AppException("商户门店订单表不存在");
        }
        if (merchantStoreOrder.getIsDel()) {
            throw new AppException("商户门店订单表不存在");
        }
        return merchantStoreOrder;
    }

    /**
    * 批量删除
    * @param idList
    * @return
    */
    @Override
    public boolean batchDelete(List<Integer> idList) {
    LambdaUpdateWrapper<MerchantStoreOrder> luw = Wrappers.lambdaUpdate();
        luw.set(MerchantStoreOrder::getIsDel, true);
        luw.in(MerchantStoreOrder::getId, idList);
        boolean update = update(luw);
        if (!update) {
            throw new AppException(CommonResultCode.ERROR.setMessage("批量删除商户门店订单表失败"));
        }
        return true;
    }

    /**
    * 查询详情
    * @param id
    * @return
    */
    @Override
    public MerchantStoreOrderDetailResponse getDetails(Integer id) {
        LambdaQueryWrapper<MerchantStoreOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(MerchantStoreOrder::getIsDel, 0);
        lqw.last("limit 1");
        MerchantStoreOrder merchantStoreOrder = this.getOne(lqw);
        if (ObjectUtil.isNotNull(merchantStoreOrder)) {
            MerchantStoreOrderDetailResponse response = new MerchantStoreOrderDetailResponse();
            BeanUtils.copyProperties(merchantStoreOrder, response);
            return response;
        }
        return null;
    }

    @Override
    public OrderNoResponse createOrder(MerchantStoreOrderFrontSaveRequest request) {
        User user = userService.getInfo();
        MerchantStoreOrder merchantStoreOrder = new MerchantStoreOrder();
        merchantStoreOrder.setUserId(user.getId());
        BigDecimal productPrice = BigDecimal.ZERO;
        String productName = "店铺二维码收款";
        merchantStoreOrder.setProTotalPrice(request.getPayPrice());
        merchantStoreOrder.setProTotalPrice(merchantStoreOrder.getProTotalPrice().setScale(2, BigDecimal.ROUND_UP));
        merchantStoreOrder.setTotalPrice(merchantStoreOrder.getProTotalPrice());
        merchantStoreOrder.setPayPrice(request.getPayPrice());

        merchantStoreOrder.setProductName(productName);

        String name = merchantService.getNameById(request.getMerchantId());
        merchantStoreOrder.setMerchantName(name);

        Order order = new Order();
        if (user.getBrandId() != 0) {
            String orderNo = CrmebUtil.getOrderNo(OrderConstants.ORDER_PREFIX_BRAND);
            order.setOrderNo(orderNo);
            order.setLevel(OrderConstants.ORDER_LEVEL_BRAND);
        }else{
            String orderNo = CrmebUtil.getOrderNo(OrderConstants.ORDER_PREFIX_PLATFORM);
            order.setOrderNo(orderNo);
            order.setLevel(OrderConstants.ORDER_LEVEL_PLATFORM);
        }
        order.setMerId(request.getMerchantId());
        order.setUid(user.getId());
        order.setTotalNum(1);
        order.setTotalPostage(BigDecimal.ZERO);
        order.setSvipDiscountPrice(BigDecimal.ZERO);
        order.setTotalPrice(merchantStoreOrder.getPayPrice());
        order.setCouponPrice(BigDecimal.ZERO);
        order.setUseIntegral(0);
        order.setIntegralPrice(BigDecimal.ZERO);
        order.setPayPrice(merchantStoreOrder.getPayPrice());
        order.setPayPostage(BigDecimal.ZERO);
        order.setPaid(false);
        order.setCancelStatus(OrderConstants.ORDER_CANCEL_STATUS_NORMAL);
        // 商户门店二维码订单
        order.setType(OrderConstants.ORDER_TYPE_MER_STORE);
        order.setMerCouponPrice(BigDecimal.ZERO);
        order.setPlatCouponPrice(BigDecimal.ZERO);
        order.setIsSvip(user.getIsPaidMember());

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderNo(order.getOrderNo());
        orderDetail.setMerId(request.getMerchantId());
        orderDetail.setUid(user.getId());
        orderDetail.setProductId(0);
        orderDetail.setProductName(merchantStoreOrder.getProductName());
        orderDetail.setAttrValueId(0);
        orderDetail.setSku("商户门店二维码");
        orderDetail.setPrice(merchantStoreOrder.getPayPrice());
        orderDetail.setPayNum(1);
        orderDetail.setWeight(BigDecimal.ZERO);
        orderDetail.setVolume(BigDecimal.ZERO);
        orderDetail.setProductType(ProductConstants.PRODUCT_TYPE_MER_STORE);
        orderDetail.setSubBrokerageType(0);
        orderDetail.setBrokerage(0);
        orderDetail.setBrokerageTwo(0);
        orderDetail.setFreightFee(BigDecimal.ZERO);
        orderDetail.setUseIntegral(0);
        orderDetail.setIntegralPrice(BigDecimal.ZERO);
        orderDetail.setPayPrice(merchantStoreOrder.getPayPrice());

        orderDetail.setIsSvip(order.getIsSvip());
        orderDetail.setIsPaidMemberProduct(false);
        orderDetail.setVipPrice(BigDecimal.ZERO);

        orderDetail.setMerCouponPrice(BigDecimal.ZERO);
        orderDetail.setPlatCouponPrice(BigDecimal.ZERO);
        orderDetail.setCouponPrice(BigDecimal.ZERO);
        orderDetail.setImage("");
        orderDetail.setPrice(productPrice);

        merchantStoreOrder.setPrice(productPrice);
        merchantStoreOrder.setOrderNo(order.getOrderNo());
        // 0待支付 1已支付
        merchantStoreOrder.setOrderStatus(0);
        merchantStoreOrder.setCreateTime(new Date());
        merchantStoreOrder.setType(1);
        save(merchantStoreOrder);

        orderService.save(order);
        orderDetailService.save(orderDetail);

        // 生成订单日志
        orderStatusService.createLog(order.getOrderNo(), OrderStatusConstants.ORDER_STATUS_CREATE, OrderStatusConstants.ORDER_LOG_MESSAGE_CREATE);

        OrderNoResponse response = new OrderNoResponse();
        response.setOrderNo(order.getOrderNo());
        response.setPayPrice(order.getPayPrice());
        response.setOrderType(OrderConstants.ORDER_TYPE_MER_STORE);
        return response;
    }

    @Override
    public void callBack(String orderNo) {
        MerchantStoreOrder traceableOrder = getByOrderNo(orderNo);
        Order order = orderService.getByOrderNo(orderNo);
        traceableOrder.setThirdOrderNo(order.getOutTradeNo());
        traceableOrder.setPayType(order.getPayType());
        traceableOrder.setPayChannel(order.getPayChannel());
        // 0-待支付 1-已支付
        if (Objects.equals(order.getPaid(), true)) {
            traceableOrder.setOrderStatus(1);
        } else {
            traceableOrder.setOrderStatus(0);
        }
        updateById(traceableOrder);

        // 绑定用户到这个店铺上，后续线上的订单就是这个店铺的
        UserStoreRelation userStoreRelation = new UserStoreRelation();
        userStoreRelation.setUserId(order.getUid());
        userStoreRelation.setMerchantId(traceableOrder.getMerchantId());
        userStoreRelation.setOrderNo(orderNo);
        LambdaQueryWrapper<Merchant> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Merchant::getName, Merchant::getCommunity, Merchant::getCommunityId);
        wrapper.eq(Merchant::getId, traceableOrder.getMerchantId());
        Merchant merchant = merchantService.getOne(wrapper);
        if (ObjectUtil.isNotNull(merchant)) {
            userStoreRelation.setCommunity(merchant.getCommunity());
            userStoreRelation.setCommunityId(merchant.getCommunityId());
            userStoreRelation.setMerchantName(merchant.getName());
        }
        userStoreRelationService.save(userStoreRelation);
    }

    private MerchantStoreOrder getByOrderNo(String orderNo) {
        LambdaQueryWrapper<MerchantStoreOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(MerchantStoreOrder::getOrderNo, orderNo);
        lqw.eq(MerchantStoreOrder::getIsDel, false);
        lqw.orderByDesc(MerchantStoreOrder::getCreateTime);
        lqw.last(" limit 1");
        return dao.selectOne(lqw);
    }

}

